package com.study.concurrent.B_ThreadSynchronizedBasic.b_UseSynchronized;

/**
 * Created by 赵超 on 2017/3/21.
 */
public class Account {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    /**
     * 将传入的数值加到余额balance中，同一时间只允许以一个线程改变这个值，所以我们使用synchronized关键字将这个方法标记为临界区
     * @param amount
     */
    public synchronized void addAmount(double amount) {
        double tmp = balance;
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tmp += amount;
        balance = tmp;
    }

    /**
     * 将传入的数字从余额中扣除，同一时间只允许以一个线程改变这个值，所以我们使用synchronized关键字将这个方法标记为临界区
     * @param amount
     */
    public synchronized void subtractAmount(double amount) {
        double  tmp = balance;
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tmp -= amount;
        balance = tmp;
    }
}
